跳到主要内容

22 括号生成

https://leetcode.cn/leetbook/read/top-interview-questions-medium/xv33m7/

cost: 6m3s

class Solution {
public:
vector<string> generateParenthesis(int n) {
vector<string> res;
string s = "";
this->walk(res, s, n, n);
return res;
}

private:
void walk(vector<string>& res, string& s, int n, int n2) {
if (n == 0 && n2 == 0) {
res.push_back(s);
return;
}w
if (n < n2) {
s.push_back(')');
this->walk(res, s, n, n2 - 1);
s.pop_back();
}
if (n > 0) {
s.push_back('(');
this->walk(res, s, n - 1, n2);
s.pop_back();
}
}
};